import 'package:shared_preferences/shared_preferences.dart';

/// 查询历史记录服务
class HistoryService {
  static const String _historyKey = 'tracking_history';
  static const int _maxHistoryCount = 20; // 最多保存20条历史记录

  /// 获取查询历史记录
  static Future<List<String>> getHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      return prefs.getStringList(_historyKey) ?? [];
    } catch (e) {
      return [];
    }
  }

  /// 添加查询历史记录
  static Future<void> addToHistory(String trackingNumber) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final history = await getHistory();
      
      // 移除重复的记录
      history.remove(trackingNumber);
      
      // 添加到最前面
      history.insert(0, trackingNumber);
      
      // 只保留最近N条
      if (history.length > _maxHistoryCount) {
        history.removeRange(_maxHistoryCount, history.length);
      }
      
      await prefs.setStringList(_historyKey, history);
    } catch (e) {
      // 忽略错误，不影响主流程
    }
  }

  /// 清除所有历史记录
  static Future<void> clearHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_historyKey);
    } catch (e) {
      // 忽略错误
    }
  }

  /// 删除单条历史记录
  static Future<void> removeFromHistory(String trackingNumber) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final history = await getHistory();
      history.remove(trackingNumber);
      await prefs.setStringList(_historyKey, history);
    } catch (e) {
      // 忽略错误
    }
  }
}

